package com.kongshidian.ui.fragment;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.annotation.view.ViewInject;

import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.kongshidian.App;
import com.kongshidian.R;
import com.kongshidian.adapter.MainProductRecommendAdapter;
import com.kongshidian.bean.BrandRecommend;
import com.kongshidian.bean.MainTopAdvertisement;
import com.kongshidian.bean.PageEntity;
import com.kongshidian.bean.Product;
import com.kongshidian.http.WebClient;
import com.kongshidian.http.WebException;
import com.kongshidian.ui.BrandListActivity;
import com.kongshidian.ui.MainActivity;
import com.kongshidian.ui.ProductDetailActivity;
import com.kongshidian.ui.view.AbsScrollGridView;
import com.kongshidian.ui.view.CountdownClock;
import com.kongshidian.ui.view.MyPagerGalleryView;
import com.kongshidian.ui.view.ScrollViewRefreshProxy;
import com.kongshidian.ui.view.CountdownClock.ClockListener;
import com.kongshidian.ui.view.MyPagerGalleryView.MyOnItemClickListener;
import com.kongshidian.ui.view.ScrollViewRefreshProxy.OnRefreshActionListener;
import com.kongshidian.util.NetworkUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;



/***
 * 顶级空时店
 * @author ghg
 *
 */
@SuppressLint("HandlerLeak")
public class TopKSDFragment extends BaseFragment implements OnRefreshActionListener{
	
	/** 顶部branner 滚动广告 */
	LinearLayout mMainPageLin; //滚动garllery
	MyPagerGalleryView mMainPageGalleryView; //滚动garllery
	LinearLayout mMainPageGalleryLin; //底部圆点容器

	/**  */
	AbsScrollGridView mBrandGridView;
	AbsScrollGridView mProductRecommendGrid;

	private MainTopAdvertisement mTopAdvertisement;
	private List<MainTopAdvertisement.AdServing> mAdServings;

	//单品推荐
	private List<Product> mRecommend;
	private MainProductRecommendAdapter mProductRecommendAdapter;
	private static final String TAG = "TopKSDFragment"; 


	PullToRefreshScrollView mPtrScrollView;
	ScrollViewRefreshProxy mScrollViewRefreshProxy;

	
	private Handler mHandler = new MyHandler(this);
	
	@Override  
	public View onCreateView(LayoutInflater inflater, ViewGroup container,  
			Bundle savedInstanceState) { 
		return inflater.inflate(R.layout.fragement_topksd, container, false);  
	}  
	
	
	
	/**
	 * 创建以后做的事情
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		
		
		/** 顶部branner 滚动广告 ,商家信息*/
		mMainPageLin	 = (LinearLayout) getView().findViewById(R.id.main_branner_lin);
		mMainPageGalleryView = 		(MyPagerGalleryView) getView().findViewById(R.id.main_branner_grally);
		mMainPageGalleryLin =		(LinearLayout) getView().findViewById(R.id.main_branner_butttom_lin);
		
		 
		
		
		/**  */
		 mBrandGridView=	(AbsScrollGridView) getView().findViewById(R.id.main_brand_gridView);
		 mProductRecommendGrid= 	(AbsScrollGridView)getView().findViewById(R.id.main_product_recommend_grid);
		
		 
			mPtrScrollView = (PullToRefreshScrollView) getView().findViewById(R.id.topksd_scroll);
		 
		 init();
		
	}

	


	private void init() {

		
		// TODO Auto-generated method stub

		mScrollViewRefreshProxy = new ScrollViewRefreshProxy(mPtrScrollView);
		mScrollViewRefreshProxy.setOnRefreshActionListener(this);
		
		//将猜你喜欢改成下拉形式 ------------------------------------
		mProductRecommendAdapter = new MainProductRecommendAdapter(getActivity(), R.layout.item_main_product_recommend);
		mProductRecommendGrid.setAdapter(mProductRecommendAdapter);

		mProductRecommendGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View view, int position, long id) {
				Intent intent = new Intent(getActivity(),ProductDetailActivity.class);
				intent.putExtra("productID", mProductRecommendAdapter.getData().get(position).getId()+"");
				startActivity(intent);
			}

		});

		mScrollViewRefreshProxy.refreshing();

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		InitData();
	}
	
	
	
	
	private void InitData() {
		if (!NetworkUtil.isNetworkConnected(getActivity())) {							// 判断是否联网

			App.showShortToast("当前未检测到网络链接");
			mScrollViewRefreshProxy.loadRefreshActionComplete();
			return;
		}
		
//		/** 获取广告 */
		getAdvertisementsAsync(); 
//		/** 获取特卖 */
//		getSpecialSaleSync();  
//		/** 品牌团购 */
//		getGrouponsRecommendAysnc();
		/** 获取9个品牌推荐 */
//		getBrandRecommendAsync();
//		/** 猜你喜欢 */
		getRecommendAsync(1);  

		
	}
	
	
	
	//Load Data Async .................................................
	/** 获取广告 */
	private void getAdvertisementsAsync() {
		new Thread(){
			public void run() {
				try {
					//获取首页头部广告
					mTopAdvertisement = WebClient.getInstance(getActivity()).adVertisement();
					mAdServings = mTopAdvertisement.getActiveServings();
					mHandler.sendEmptyMessage(0);
				} catch (Exception e) {
					mAdServings = new ArrayList<MainTopAdvertisement.AdServing>();
					mHandler.sendEmptyMessage(0);
					Log.w(TAG, "Get advertisement fail," + e.toString());
				}
			};
		}.start();
	}
	
	
	

	
	
	
	
	
	/** 首页单品推荐  */
	private void getRecommendAsync(final int pageNumber) {
		new Thread(){
			public void run() {
				try {
					PageEntity<Product> entry = WebClient.getInstance(getActivity()).getRecommend(pageNumber);

					mRecommend = entry.getContent();

					mHandler.sendEmptyMessage(4);
				} catch (WebException e) {
					App.showLog("Get Recommand fail=="+e.toString());
				}catch (Exception e) {
					App.showLog("Get Recommand fail=="+e.toString());
					App.showShortToast("未知错误");					
				}
			};
		}.start();


	}
	
	//Load Data Async End.................................................
		
		
		
		/**
		 * Handle下载
		 * @author ghg
		 *
		 */
		private  class MyHandler extends Handler{


			private final WeakReference<Fragment> mActivity; // activity弱引用

			public MyHandler(TopKSDFragment topKSDFragment) {  
				mActivity = new WeakReference<Fragment>(topKSDFragment);  
			}  

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				if( mActivity.get() != null ){ //activity若已销毁。不做任何处理
					switch (msg.what) {
					case 0:
						//获取广告
						initBranner();
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;

					case 1:
						//获取特卖 
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;

					case 3:
						//9个品牌推荐viewpage
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;
					case 4:
						//单品推荐
						mProductRecommendAdapter.update(mRecommend);
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;
					case 5:
						mScrollViewRefreshProxy.loadRefreshActionComplete();
						break;

					default:
						break;
					}
				}
			}
			
		
		}
		
		/** 初始化顶部branner滚动视图 */
		private void initBranner() {
			//判空。。
			if(mAdServings == null || mAdServings.size() == 0 ){
				mMainPageLin.setVisibility(View.GONE);
				return;
			}

			String[] urlImageList  = new String[mAdServings.size()];
			for (int i = 0; i < mAdServings.size(); i++) {
				urlImageList[i] = mAdServings.get(i).getAdMaterial().getPath();
			}	     

				mMainPageGalleryView.start(getActivity(), urlImageList, 3000,
				mMainPageGalleryLin, R.drawable.dot_focused, R.drawable.dot_normal);

				mMainPageGalleryView.setMyOnItemClickListener(new MyOnItemClickListener() {
				public void onItemClick(int curIndex) {
					App.showLog("下标=="+curIndex);
				}
			});
			
		}
		

		
		

		
		
		
		
		
		
		
		
		
		


		
		
			@Override
			public void onStop() {
				// TODO Auto-generated method stub
				mMainPageGalleryView.stopTimer();
				super.onStop();
			}
			
			@Override
			public void onDestroy() {
				super.onDestroy();
				mHandler.removeCallbacksAndMessages(null);
			}
		
}
